package com.mobilesales.android;

import java.io.IOException;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.mobilesales.android.activities.clients.Clients;
import com.mobilesales.android.activities.common.SettingsActivity;
import com.mobilesales.android.activities.employees.Messages;
import com.mobilesales.android.activities.orders.Orders;
import com.mobilesales.android.activities.products.Products;
import com.mobilesales.android.activities.tasks.Tasks;
import com.mobilesales.android.c2dm.C2DMMessaging;
import com.mobilesales.android.c2dm.C2DMReceiver;
import com.mobilesales.android.c2dm.NotificationReceiver;
import com.mobilesales.android.c2dm.parsers.MessageParser;
import com.mobilesales.android.infrastructure.Language;
import com.mobilesales.android.infrastructure.MenuBuilder;
import com.mobilesales.android.infrastructure.MenuItem;
import com.mobilesales.android.infrastructure.SyncTask;
import com.mobilesales.android.model.employees.EmployeeAccess;
import com.mobilesales.android.services.AuthServiceClient;
import com.mobilesales.android.services.Configuration;
import com.mobilesales.android.util.Constants;
import com.mobilesales.android.util.LogFlags;
import com.mobilesales.android.util.MessageBox;
import com.mobilesales.android.util.Settings;
import com.mobilesales.android.util.Settings.UnformatedEndpoints;

public class MobileSalesActivity extends ListActivity {

	private ArrayAdapter<MenuItem> menuItems;
	private Handler handler = new Handler();
	private ProgressDialog progressDialog;
	
	private NotificationReceiver notificationReceiver;
	private MessageParser messageParser;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Settings settings = Settings.getSettings();
		this.initLanguage(settings);
		
		setContentView(R.layout.main);

		MobileSalesActivity.this.buildMenu(settings);
		messageParser = new MessageParser(this);
		if (settings == null) {
			this.startActivityForResult(
				new Intent(this, SettingsActivity.class), Constants.RequestCodes.ChangeSettings);
		}
		else {
			this.init();
		}
	}
	
	private void initLanguage(Settings settings) {
		if (settings!=null) {
			String lang = settings.getLanguage();
			if (lang!=null && !lang.equals("")) {
				Language.setCurrentLanguage(this, lang);
			}
		}
	}
	
	private NotificationReceiver createNotificationReceiver() {
		return new NotificationReceiver(handler) {
			@Override
			public void onRegistered(String registrationId) {
				init(registrationId);
			}
			
			@Override
			public void onMessage(String message) {
				Boolean success = messageParser.parseMessage(message);
				Log.i("refreshing", "success:"+success);
				MessageBox.show(MobileSalesActivity.this,  getString(R.string.Refreshing));
			}
			
			@Override
			public void onError(String errorId) {
				Log.e("NotificationReceiver", "onError: "+errorId);
				MessageBox.show(MobileSalesActivity.this, MobileSalesActivity.this.getString(R.string.ErrorC2DMRegistration));
			}
		};		
	}
	
	private void init() {
		if (notificationReceiver==null)
			notificationReceiver = this.createNotificationReceiver();
		C2DMMessaging.addNotificationReceiver(notificationReceiver);
		
		Settings settings = Settings.getSettings();
		if (settings==null)
			return;
		
		//if (settings.getC2dmRegistrationId().equals("")) {
			String serverMail = settings.getC2dmServerMail();
	    	C2DMReceiver.senderId = serverMail;
	    	//Log.i("C2DM - register", "senderId:"+serverMail);
			C2DMMessaging.register(this, serverMail);
		//}
		//else
		//	this.init(settings.getC2dmRegistrationId());
	}

	private void init(final String c2dmRegistrationId) {
		final Settings settings = Settings.getSettings();
		
		try {
			settings.setC2dmRegistrationId(c2dmRegistrationId);
			settings.save();
		} catch (IOException e1) {
			Log.e("c2dm", e1.getMessage(), e1);
			MessageBox.show(MobileSalesActivity.this, MobileSalesActivity.this.getString(R.string.ErrorSave));
			return;
		}

		Thread thread = new Thread() {
			public void run() {
				if (settings != null) {
					
					handler.post(new Runnable() {
						public void run() {
							progressDialog = ProgressDialog.show(MobileSalesActivity.this, null, MobileSalesActivity.this.getText(R.string.LoggingIn));
						}
					});
					EmployeeAccess access = MobileSalesActivity.this.login(settings.getServerUrl(),
							settings.getLogin(), settings.getPassword(), c2dmRegistrationId);
					if (access != null) {

						settings.setC2dmRegistrationId(c2dmRegistrationId);
						settings.setEmployeeId(access.EmployeeId);
						settings.setToken(access.Token);
						try {
							settings.save();
							handler.post(new Runnable() {
								public void run() {
									progressDialog.dismiss();
									MobileSalesActivity.this.syncCheck(settings);
								}
							});
						} catch (IOException e) {
							Log.e("Save settings", e.getMessage(), e);
						}
					} else {
						handler.post(new Runnable() {
							public void run() {
								progressDialog.dismiss();
								MessageBox.show(MobileSalesActivity.this, getString(R.string.ErrorLogin));
							}
						});
					}
				}
			}
		};
		thread.start();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (this.notificationReceiver!=null)
			C2DMMessaging.removeNotificationReceiver(notificationReceiver);
	}

	public void buildMenu(Settings settings) {
		MenuBuilder mbuilder = new MenuBuilder(this);
		if (settings != null) {
			mbuilder.addItem(new MenuItem(Products.class, getString(R.string.Products)))
					.addItem(new MenuItem(Clients.class,getString(R.string.Clients)))
					.addItem(new MenuItem(Tasks.class, getString(R.string.Tasks)))
					.addItem(new MenuItem(Orders.class, getString(R.string.Orders)))
					.addItem(new MenuItem(Messages.class,getString(R.string.Messages)));
		}
		menuItems = mbuilder.addItem(new MenuItem(SettingsActivity.class,getString(R.string.Settings))).build();
		this.setListAdapter(menuItems);
	}

	public void syncCheck(Settings settings) {
		if (settings != null && settings.isSyncOnStart()) {
			SyncTask task = new SyncTask(this);
			task.execute();
		}
	}

	@Override
	protected void onListItemClick(ListView listView, View view, int position,
			long id) {
		super.onListItemClick(listView, view, position, id);
		MenuItem menuItem = (MenuItem) this.menuItems.getItem(position);
		Intent intent = new Intent(this, menuItem.getActivityClass());
		if (SettingsActivity.class.equals(menuItem.getActivityClass())) {
			this.startActivityForResult(intent, Constants.RequestCodes.ChangeSettings);
		}
		else {
			this.startActivity(intent);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == Constants.RequestCodes.ChangeSettings) {
			if (data!=null && data.getExtras()!=null) {
				Bundle extra = data.getExtras();
				if (extra.containsKey(Constants.SettingsChanged)) {
					boolean changed = extra.getBoolean(Constants.SettingsChanged);
					if (!changed) {
						return;
					}
				}
			}
			setContentView(R.layout.main);
			Settings settings = Settings.getSettings();
			MobileSalesActivity.this.buildMenu(settings);
			if (settings!=null)
				this.init();
		}
	}
	
	private EmployeeAccess login(String serverUrl, String username,
			String password, String c2dmRegId) {
		String url = String.format(UnformatedEndpoints.AuthEndpoint, serverUrl);
		Configuration conf = new Configuration(url);
		AuthServiceClient authService = new AuthServiceClient(conf);
		EmployeeAccess access = null;
		try {
			access = authService.Login(username, password, c2dmRegId);
		} catch (Exception e) {
			Log.e(LogFlags.RestService, "Could not login on server", e);
		}
		return access;
	}

}
